﻿using System;
using System.Globalization;
using System.Text;
using System.Net;
using RFDeviceNet;


namespace DemoSharp
{
    class Program
    {
        private const string MainMenu = "****************************************************\r\nPress key to select:\r\n" +
                                        "1 - Test 620 device.\r\n" +
                                        "2 - Test 603 device.\r\n" +
                                        "3 - Test 625 device.\r\n" +
                                        "Other - Exit.";

        private static PacketWorker _pworker;

        static void Main(string[] args)
        {
            _pworker = new PacketWorker();
            var init = RFDeviceObjectNet.Initialize();
            if (!init)
            {
                Console.WriteLine("RFDeviceObject initializing failed. Program will exit.");
                Console.Read();
                return;
            }
            Console.WriteLine("Library version - " + RFDeviceObjectNet.RFDevice_GetVersionString());
            while (true)
            {
                Console.WriteLine(MainMenu);
                var key = Console.ReadKey();
                Console.WriteLine();
                if (key.Key == ConsoleKey.D1 || key.Key == ConsoleKey.NumPad1)
                    Go620Test();
                else if (key.Key == ConsoleKey.D2 || key.Key == ConsoleKey.NumPad2)
                    Go603Test();
                else if (key.Key == ConsoleKey.D3 || key.Key == ConsoleKey.NumPad3)
                    Go625Test();
                else
                {
                    break;
                }
            }
        }


        static void Go625Test()
        {
            Console.WriteLine("625 test...");

            _UDP_DEVINFOBLOCK_PC_Net block;
            try
            {
                block = _pworker.GetUdpPcketFrom620();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            var dev = RF625DeviceNet.CreateRF625Device(block);
            var sb = new StringBuilder();
            foreach (var b in block.IP)
            {
                sb.Append(b.ToString(CultureInfo.InvariantCulture) + '.');
            }
            sb.Remove(sb.Length - 1, 1);
            if (dev.Connect())
            {
                Console.WriteLine("Connected to 625 device " + sb + '.');
                Console.WriteLine(dev.ReadParams()
                                      ? "Parameters reading from 625 device done."
                                      : "Can't read parameters from 625 device.");
                Console.WriteLine(dev.WriteParams()
                                      ? "Parameters writing to 625 device done."
                                      : "Can't write parameters to 625 device.");
                var tcpResultBuffer = new Byte[0];
                if (dev.GetResult(ref tcpResultBuffer, false))
                {
                    Console.WriteLine("TCP GetResult operation result:");
                    int i = 0;
                    foreach (var b in tcpResultBuffer)
                    {
                        Console.Write("{0,3:D}", b);
                        if (i > 9)
                        {
                            i = 0;
                            Console.WriteLine();
                        }
                        else
                        {
                            i++;
                            Console.Write(" ");
                        }
                    }
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine("TCP GetResult operation error.");
                }
                Console.WriteLine(dev.Disconnect() ? "625 device disconnected." : "625 device disconnect error.");
            }
            else
            {
                Console.WriteLine("TCP connecting to 625 device failed.");
            }

            while (true)
            {
                Console.WriteLine("Input local IP for UDP working with 625 device. Use 'Enter' when complete.");
                var ip = Console.ReadLine();
                Console.WriteLine();
                IPAddress ipAddress;
                if (ip == null || IPAddress.TryParse(ip, out ipAddress) == false)
                {
                    Console.WriteLine("Wrong ip.");
                }
                else
                {
                    Console.WriteLine("Current ip: " + ipAddress);
                    if (!dev.UDPConnect(6001, ipAddress.ToString()))
                    {
                        Console.WriteLine("Can't connect with 625 device via UDP.");
                        break;
                    }
                    var udpBuf = new byte[0];
                    if (!dev.UDPGetResult(ref udpBuf, false))
                    {
                        Console.WriteLine("Can't get result from 625 device via UDP.");
                        break;
                    }
                    int i = 0;
                    foreach (var b in udpBuf)
                    {
                        Console.Write("{0,3:D}", b);
                        if (i > 9)
                        {
                            i = 0;
                            Console.WriteLine();
                        }
                        else
                        {
                            i++;
                            Console.Write(" ");
                        }
                    }
                    if (!dev.Disconnect())
                    {
                        Console.WriteLine("Can't disconnect from 625 device via UDP.");
                        break;
                    }
                    Console.WriteLine("Disconnected from 625 device via UDP.");
                    break;
                }
            }
        }

        static void Go620Test()
        {
            Console.WriteLine("620 test...");
            
            _UDP_DEVINFOBLOCK_PC_Net block;
            try
            {
                block = _pworker.GetUdpPcketFrom620();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            var dev = RF620DeviceNet.CreateRF620Device(block);
            var sb = new StringBuilder();
            foreach (var b in block.IP)
            {
                sb.Append(b.ToString(CultureInfo.InvariantCulture) + '.');
            }
            sb.Remove(sb.Length - 1, 1);
            if (dev.Connect())
            {
                Console.WriteLine("Connected to 620 device " + sb + '.');
                Console.WriteLine(dev.ReadParams()
                                      ? "Parameters reading from 620 device done."
                                      : "Can't read parameters from 602 device.");
                Console.WriteLine(dev.WriteParams()
                                      ? "Parameters writing to 620 device done."
                                      : "Can't write parameters to 602 device.");
                var tcpResultBuffer = new Byte[0];
                if (dev.GetResult(ref tcpResultBuffer))
                {
                    Console.WriteLine("TCP GetResult operation result:");
                    int i = 0;
                    foreach (var b in tcpResultBuffer)
                    {
                        Console.Write("{0,3:D}", b);
                        if (i > 9)
                        {
                            i = 0;
                            Console.WriteLine();
                        }
                        else
                        {
                            i++;
                            Console.Write(" ");
                        }
                    }
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine("TCP GetResult operation error.");
                }
                Console.WriteLine(dev.Disconnect() ? "620 device disconnected." : "620 device disconnect error.");
            }
            else
            {
                Console.WriteLine("TCP connecting to 620 device failed.");
            }

            while (true)
            {
                Console.WriteLine("Input local IP for UDP working with 620 device. Use 'Enter' on complete.");
                var ip = Console.ReadLine();
                Console.WriteLine();
                IPAddress ipAddress;
                if (ip == null || IPAddress.TryParse(ip, out ipAddress) == false)
                {
                    Console.WriteLine("Wrong ip.");
                }
                else
                {
                    Console.WriteLine("Current ip: " + ipAddress);
                    if (!dev.UDPConnect(6001, ipAddress.ToString()))
                    {
                        Console.WriteLine("Can't connect with 620 device via UDP.");
                        break;
                    }
                    var udpBuf = new byte[0];
                    if (!dev.UDPGetResult(ref udpBuf))
                    {
                        Console.WriteLine("Can't get result from 620 device via UDP.");
                        break;
                    }
                    int i = 0;
                    foreach (var b in udpBuf)
                    {
                        Console.Write("{0,3:D}", b);
                        if (i > 9)
                        {
                            i = 0;
                            Console.WriteLine();
                        }
                        else
                        {
                            i++;
                            Console.Write(" ");
                        }
                    }
                    if (!dev.Disconnect())
                    {
                        Console.WriteLine("Can't disconnect from 620 device via UDP.");
                        break;
                    }
                    Console.WriteLine("Disconnected from 620 device via UDP.");
                    break;
                }
            }
        }

        static void Go603Test()
        {
            Console.WriteLine("603 test...");
            var dev = RF603DeviceNet.CreateRF603Device();
            dev.BindNetworkAddress(1);
            int comNum;
            while (true)
            {
                Console.WriteLine("Input COM port number for 603 device connection. Press 'Enter' to complete.");
                var comNumStr = Console.ReadLine();
                if (string.IsNullOrEmpty(comNumStr) || !int.TryParse(comNumStr, out comNum))
                {
                    Console.WriteLine("Wrong number.");
                }
                else
                {
                    break;
                }
            }
            if (!dev.OpenPort("COM" + comNum.ToString(CultureInfo.InvariantCulture), 9600))
            {
                Console.WriteLine("OpenPort operation error.");
                return;
            }
            var ps = new _RF60x_HELLO_ANSWER_Net();
            if (!dev.HelloCmd(1, ref ps))
            {
                Console.WriteLine("HelloCmd opearion error.");
            }
            else
            {
                Console.WriteLine("Device serial: " + ps.DeviceSerial);
                Console.WriteLine("Device max distance: " + ps.DeviceMaxDistance);
            }
            ushort value = 0;
            if (!dev.Measure(1, ref value))
            {
                Console.WriteLine("Can't get measure from 603 device.");
            }
            Console.WriteLine("Read measure value: " + value.ToString(CultureInfo.InvariantCulture));

            if (!dev.StartStream(1))
            {
                Console.WriteLine("Can't start stream from 603 device.");
            }
            else
            {
                for (int i = 0; i < 10; i++)
                {
                    if(dev.GetStreamMeasure(ref value))
                        Console.Write(value + " ");
                    else
                    {
                        Console.Write("GetStreamMeasureError.");
                        break;
                    }
                }
                Console.WriteLine();
                Console.WriteLine(!dev.StopStream(1) ? "StopStream operation error." : "StopStream operation complete.");
                Console.WriteLine(!dev.ClosePort() ? "ClosePort operation error." : "ClosePort operation complete.");
            }

        }
    }
}
